<template>
  <div id="index" ref="appRef">
    <div class="bg">
      <dv-loading v-if="loading">Loading...</dv-loading>
      <div v-else class="host-body">
        <div class="full-players">
          <div class="bottom-layer">
            <view v-if="isLoadingAgain" class="loading-again">
              <!-- <a-spin size="large" /> -->
              <dv-loading>Loading...</dv-loading>
            </view>
            <MapView ref="mapView" v-if="!isLoadingAgain" :defects="defectInfoList" @click-marker="handlePressMarker"
              :map-mode="mapMode">
            </MapView>
          </div>
          <div class="tools-top">
            <div class="d-flex jc-center">
              <dv-decoration-10 class="dv-dec-10" />
              <div class="d-flex jc-center">
                <dv-decoration-8 class="dv-dec-8" />
                <div class="title title-top">
                  <!-- <span class="title-text">{{ title }}</span> -->
                  <!-- <span class="title-text titla-area"> -->
                  <div class="title-area">
                    <img :src="titleLogo" style="width: 480px; height: 60px;" />
                    <!-- <text>智能检测平台</text> -->
                  </div>
                  <!-- </span> -->
                  <dv-decoration-6 class="dv-dec-6" :reverse="true" :color="['#50e3c2', '#67a1e5']" />
                </div>
                <dv-decoration-8 class="dv-dec-8" :reverse="true" />
              </div>
              <dv-decoration-10 class="dv-dec-10-s" />
            </div>
            <div class="d-flex jc-between px-2">
              <div class="d-flex aside-width">
                <div class="react-left ml-4 react-l-s">
                  <span class="react-before">

                  </span>
                  <span class="text">{{ subtitle[0] }}</span>

                </div>
                <div class="react-left ml-3">
                  <span class="text">{{ subtitle[1] }}</span>
                  <span class="text"></span>
                </div>
              </div>
              <div class="d-flex aside-width">
                <div class="react-right  mr-3">
                  <span class="text fw-b">{{ subtitle[2] }}</span>
                </div>
                <div class="react-right mr-4 react-l-s">
                  <span class="react-after"></span>
                  <span class="text time-text">
                    {{ timeInfo.dateYear }} {{ timeInfo.dateWeek }}
                    {{ timeInfo.dateDay }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="tools-left">
            <div>
              <dv-border-box-12>
                <LbmLeftPads :number1="totalInfo.allStats" :number2="totalInfo.allRoute" />
              </dv-border-box-12>
            </div>

            <div>
              <dv-border-box-13 style="height:410px">
                <LbmLeftPie v-if="categoryList.length > 0" :series-data="categoryList" />
              </dv-border-box-13>
            </div>

            <div>
              <dv-border-box-10>
                <LbmLeftBottom ref="lbmLeftBottomRef" />
              </dv-border-box-10>
            </div>
          </div>

          <div class="tools-right">
            <div>

              <!-- <LbmRightTerms /> -->
              <!-- <div class="right-top">
                <a-button type="primary" @click="handlePressAI">智能小鹿</a-button>
                <a-button type="primary" @click="handlePressCreator">智能创作</a-button>
              </div> -->


              <div class="centerRight2">
                <div class="map-modes">
                  <a-radio-group v-model:value="mapMode" @change="handleMapModeChange">
                    <a-radio-button value="standard">标准地图</a-radio-button>
                    <a-radio-button value="satellite">卫星图</a-radio-button>
                  </a-radio-group>
                </div>
                <!-- <div class="terms-row">
                  <a-input class="theInput" placeholder="搜索位置" v-model:value="keyword" />
                </div> -->
                <div class="cascader-row">
                  <a-cascader class="theCascader" :field-names="{ label: 'name', value: 'id', children: 'children' }"
                    :size="'small'" :allowClear="true" v-model:value="cascaderValue" :options="cascaderOptions"
                    :load-data="loadCascaderData" placeholder="请选择" @change="handleCascaderChange">
                    <template v-slot:clearIcon>
                      <div>
                        <CloseCircleOutlined />
                      </div>
                    </template>
                  </a-cascader>
                </div>
                <div class="select-option">
                  <a-select class="selectData" v-model:value="taskValue" :fieldNames="{ label: 'name', value: 'id' }"
                    size="small" :allowClear="true" :autoClearSearchValue="false" :show-search="true"
                    :filter-option="false" :default-active-first-option="false" :show-arrow="false" placeholder="请选择任务单"
                    @search="handleTaskSearch" :options="taskOptions" @change="handleTaskChange">
                    <template v-slot:clearIcon>
                      <div>
                        <CloseCircleOutlined />
                      </div>
                    </template>
                  </a-select>
                </div>
                <div class="select-option">
                  <a-select class="selectData" v-model:value="roadValue" :fieldNames="{ label: 'name', value: 'id' }"
                    :options="roadOptions" size="small" :allowClear="true" :autoClearSearchValue="false"
                    :filter-option="false" :default-active-first-option="false" :show-arrow="false" show-search
                    placeholder="请选择路段" @search="handleRoadSearch" @change="handleRoadChange">
                    <template v-slot:clearIcon>
                      <div>
                        <CloseCircleOutlined />
                      </div>
                    </template>
                  </a-select>
                </div>
                <div class="select-option">
                  <a-select class="selectData" size="small" :allowClear="true" v-model:value="defectTypeValue"
                    :options="defectTypeOptions" mode="multiple" placeholder="请选择类型"></a-select>
                </div>
                <div class="range-row">
                  <a-range-picker class="theDatePicker" :placeholder="['开始时间', '结束时间']" v-model:value="selectedRange">
                    <template v-slot:clearIcon>
                      <div>
                        <CloseCircleOutlined />
                      </div>
                    </template>
                  </a-range-picker>
                </div>

                <!-- <div class="categories-row">
                  <a-checkbox-group v-model:value="selectedCategories" name="checkboxgroup" :options="plainOptions" />
                </div> -->

                <div class="button-row">
                  <a-button type="primary" @click="handlePressSearch">查询</a-button>
                  <a-button type="primary" style="margin-left: 10px;" @click="handlePressClear">清空</a-button>
                </div>
              </div>

              <dv-border-box-12 style="height:540px">
                <LbmRight :defects="defectInfoList" :pagination="defectPages" :loading="isDefectInfoDataLoading"
                  @double-click-defect-row="handleDoubleClickDefectRow" @click-defect-row="handleClickDefectRow"
                  @page-change="onPageChange" />
              </dv-border-box-12>
            </div>
          </div>
          <!--here-->
          <!-- <div class="top-layer">

          </div> -->
        </div>
      </div>
    </div>

    <a-modal v-model:visible="creatorModalVisible" title="智能创作" @ok="handleCreatorOk" :width="800">
      <div>
        <SlidesCreator v-if="creatorModalVisible"></SlidesCreator>
      </div>
    </a-modal>

    <a-modal v-model:visible="modalVisible" :title="selectedDefect ? selectedDefect.defect_type : ''" @ok="handleOk"
      @afterClose="handleAfterClose" :footer="null">
      <a-spin :spinning="isDefectImageLoaded" style="width: 100%; height: 100%">

        <div class="defect-modal" v-if="selectedDefect">
          <p><span :style="{ width: '100px', display: 'inline-block' }">位置：</span>{{ selectedDefect.route }}</p>
          <p><span :style="{ width: '100px', display: 'inline-block' }">经度：</span>{{ selectedDefect.longitude }}</p>
          <p><span :style="{ width: '100px', display: 'inline-block' }">纬度：</span>{{ selectedDefect.latitude }}</p>
          <p><span :style="{ width: '100px', display: 'inline-block' }">检测时间：</span>{{ selectedDefect.snapAt }}</p>
          <p><span :style="{ width: '100px', display: 'inline-block' }">类型：</span>
            <a-tag v-for="item in getDefectTypeName()" :key="item" style="margin-right: 10px;" color="orange">
              {{ item }}
            </a-tag>
          </p>
          <div class="image-area">
            <!--  ref="imageArea" -->

            <!-- <a-image :width="400" :src="getImageUrl" :preview="{
        visible: previewVisible,
        onVisibleChange: setPreviewVisible,
        src: getPreviewImageUrl
      }" /> -->
            <canvas :ref="(el) => {
        if (el) canvas = el
      }
        " style="display: none;"></canvas>

            <a-image :width="400" :src="imageSrc" :preview="{
        visible: previewVisible,
        onVisibleChange: setPreviewVisible,
        src: imageSrc
      }" />
          </div>

          <div class="buttons">
            <a-button type="primary" shape="circle" class="modal-button" @click="handlePressZoom">
              <template #icon>
                <MonitorOutlined />
              </template>
            </a-button>

            <!-- <a-button type="primary" shape="circle" class="modal-button" @click="handlePressNavi">
              <template #icon>
                <SendOutlined />
              </template>
            </a-button> -->

          </div>
        </div>
      </a-spin>
    </a-modal>


    <a-drawer v-model:visible="drawerVisible" class="custom-class" title="智能小鹿" placement="right" :maskClosable="false"
      @after-visible-change="afterDrawerVisibleChange">
      <div>
        <DeerChat></DeerChat>
      </div>
    </a-drawer>


  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  computed,
  watch,
  nextTick,
  onBeforeUnmount,
} from 'vue'

import useDraw from '@/utils/useDraw'
import qs from 'qs';
import type { Dayjs } from 'dayjs';

import { formatTime, isMoreThan3DaysFunction, setLargeItem } from '@/utils/index'
import { WEEK } from '@/constant/index'
import { title, subtitle } from '@/constant/index'
import { addData, getData, removeData } from '@/utils/indexedDBService'
import titleLogo from '@/assets/title-top.png'
import LbmLeftPads from '../lbm-left/index-pads.vue'
import LbmLeftPie from '../lbm-left/index-pie.vue'
import LbmLeftBottom from '../lbm-left-bottom/index.vue'
import LbmRight from '../lbm-right/index.vue'

import MapView from '../map/MapView.vue'
import DeerChat from '../deer/DeerChat.vue'
import SlidesCreator from '../deer/SlidesCreator.vue';

import { SendOutlined, MonitorOutlined, CloseCircleOutlined } from '@ant-design/icons-vue';
import { CascaderProps, message } from 'ant-design-vue';
import axios from 'axios';

type RangeValue = [Dayjs, Dayjs];

//不可变数据
// const plainOptions = ['坑槽', '横向裂缝', '纵向裂缝', '网状裂缝',];

//ref数据
// * 加载标识
const mapView = ref<InstanceType<typeof MapView>>()
const loading = ref<boolean>(true)
const isLoadingAgain = ref<boolean>(false)

// const defectList = ref<any[]>([])
const defectInfoList = ref<any[]>([])

const lbmLeftBottomRef = ref()
const isDefectInfoDataLoading = ref(true)
const defectPages = reactive({
  current: 1,
  total: 0,
  pages: 0,
  pageSize: 20,
  showSizeChanger: false,
})

const selectedDefect = ref<any | undefined>(undefined)
const selectedDefectInfo = ref<any | undefined>(undefined)

const totalInfo = ref<any | undefined>(undefined)
const categoryList = ref<any[]>([])
const routeList = ref<any[]>([])
const modalVisible = ref<boolean>(false);
const previewVisible = ref<boolean>(false);

const defectTypeValue = ref([])
const defectTypeOptions = [
  {
    value: 1,
    label: '纵向裂缝',
  },
  {
    value: 2,
    label: '横向裂缝',
  },
  {
    value: 3,
    label: '坑槽',
  },
  {
    value: 6,
    label: '网状裂缝',
  },
  {
    value: 7,
    label: '修补裂缝',
  },
  {
    value: 8,
    label: '修补坑槽',
  },
  {
    value: 10,
    label: '井盖',
  },
  {
    value: 11,
    label: '抛洒物',
  },
  {
    value: 12,
    label: '修补网状裂缝',
  },
  {
    value: 13,
    label: '伸缩接缝',
  },
]

const taskName = ref()
const roadName = ref()

const taskOptions = ref([])
const roadOptions = ref([])

const taskValue = ref([]);
const roadValue = ref([]);

const keyword = ref<string>('');
const selectedCategories = ref<string[]>([]);
const selectedRange = ref<RangeValue>();
const mapMode = ref<string>('standard');

const canvas = ref(null);

const imageSrc = ref()

const canvasWidth = ref<number>(2000);
const isDefectImageLoaded = ref(false)

// * 时间内容
const timeInfo = reactive({
  setInterval: 0,
  dateDay: '',
  dateYear: '',
  dateWeek: ''
})

const cascaderOptions = ref([]);
// '4', '14', '223'
const cascaderValue = ref<string[]>([]);

// * 适配处理
const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw()

const setPreviewVisible = (value): void => {
  previewVisible.value = value;
};

// const getImageUrl = computed(() => {
//   if (!selectedDefect.value) {
//     return "https://www.baidu.com/img/flexible/logo/pc/result@2.png";
//   }

//   console.log('selectedDefect.value', selectedDefect.value)
//   const imageName = selectedDefect.value.defect_in_img;
//   const url = `http://220.194.128.226:39005/infoimg?imageFile=${imageName}&size=5`
//   return url;
// })

// const getPreviewImageUrl = computed(() => {
//   if (!selectedDefect.value) {
//     return "https://www.baidu.com/img/flexible/logo/pc/result@2.png";
//   }

//   // console.log('selectedDefect.value', selectedDefect.value)
//   const imageName = selectedDefect.value.defect_in_img;
//   const url = `http://220.194.128.226:39005/infoimg?imageFile=${imageName}&size=2`

//   return url;
// })

const handleTaskSearch = (val) => {
  // console.log("handleTaskSearch ==>", val)
  loadTaskData(val)

}

const handleRoadSearch = (val) => {
  loadRoalData(val)
}

const handleTaskChange = (val) => {

  const data = taskOptions.value.find(item => item.id == val)
  console.log("data==>", data)
  if (!data || !data.name) {
    taskName.value = null
    taskValue.value = []
    loadRoalData(undefined)
    return
  }
  taskName.value = data.name
  taskValue.value = [data.id]
  loadRoalData(undefined)
}

const handleRoadChange = (val) => {

  const data = roadOptions.value.find(item => item.id == val)

  if (!data || !data.name) {
    roadName.value = null
    roadValue.value = []
    return
  }
  roadName.value = data.name
  roadValue.value = [data.id]
}

const showModal = () => {
  modalVisible.value = true;
};

const handleOk = (e: MouseEvent) => {
  console.log(e);
  modalVisible.value = false;
};

const handlePressZoom = () => {
  setPreviewVisible(true)
}

// const handlePressNavi = () => {
//   if (!selectedDefect.value) {
//     return;
//   }
//   window.open(`https://uri.amap.com/navigation?from=111.096439,36.411827,蒲县&to=${selectedDefect.value.longitude},${selectedDefect.value.latitude},${selectedDefect.value.route}`);
// }

watch(() => modalVisible.value, (newVal) => {
  if (newVal) {
    nextTick(() => {
      drawRectAndText();
    });
  }
});

// Watch for selectedDefect change to trigger redraw
// watch(() => selectedDefect.value, (newVal) => {
//   if (modalVisible.value && newVal) {
//     nextTick(() => {
//       drawRectAndText();
//     });
//   }
// });

// const getImageDefectCoordData = async () => {
//   const url = `http://220.194.128.226:39005/infoimgdefect?imageFile=${selectedDefect.value.defect_in_img}`
//   const response = await fetch(url);
//   const defectsJSONData = await response.json();
//   if (!defectsJSONData || !defectsJSONData.defects) {
//     return []
//   }
//   return defectsJSONData.defects
// }

// const imageArea = ref<HTMLDivElement | null>(null);
// const imageWidth = ref()
const loadImage = (src: string): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous'; // 允许跨域加载
    img.onload = () => resolve(img);
    img.onerror = (error) => reject(error);
    img.src = src;
  });
};


const drawRectAndText = async () => {
  // console.log("selectedDefect.value 123 000==>", selectedDefect.value)
  try {
    if (canvas.value && selectedDefect.value) {
      isDefectImageLoaded.value = true
      const context = canvas.value.getContext('2d');
      if (!context) {
        return
      }
      const img = await loadImage(selectedDefect.value.imageFile);

      const imgWidth = img.width;
      const imgHeight = img.height;
      canvasWidth.value = imgWidth;

      canvas.value!.width = imgWidth;
      canvas.value!.height = imgHeight;

      context.clearRect(0, 0, canvas.value!.width, canvas.value!.height);
      context.drawImage(img, 0, 0, imgWidth, imgHeight);

      if (selectedDefect.value.defects.length == 0) {
        imageSrc.value = selectedDefect.value.imageFile
        isDefectImageLoaded.value = false
        return
      }
      selectedDefect.value.defects.map(item => {
        const { height, left, top, width } = item.defect_rect;
        context.beginPath();
        // context.rect(left / 2, top / 2, width / 2, height / 2);
        context.rect(left, top, width, height);
        context.strokeStyle = item.event_type_color || 'red';
        context.lineWidth = 8;
        context.stroke();
        context.font = '72px Arial';
        context.fillStyle = item.event_type_color || 'red';
        // context.fillText(item.event_type_name, left / 2, top / 2 - 5);
        context.fillText(item.event_type_name, left, top - 20);
      })
      const dataURL = canvas.value.toDataURL('image/png')
      imageSrc.value = dataURL;
      isDefectImageLoaded.value = false
    }
  } catch (error) {
    isDefectImageLoaded.value = false
  }
}

const getDefectTypeName = () => {
  let list = []
  selectedDefect.value.defects.map(item => {
    list.push(item.event_type_name)
  })
  return Array.from(new Set(list));
}

const handleMapModeChange = () => {
  // console.log('handleMapModeChange')

  isLoadingAgain.value = true
  setTimeout(() => {
    isLoadingAgain.value = false
  }, 1000)
}


// 生命周期
onMounted(() => {

  loadData()
  handleTime()
  // todo 屏幕适应
  windowDraw()
  calcRate()
})

const handleAfterClose = () => {
  imageSrc.value = null
}

onUnmounted(() => {
  unWindowDraw()
  clearInterval(timeInfo.setInterval)
})

onBeforeUnmount(() => {
  unWindowDraw()
  clearInterval(timeInfo.setInterval)
})


const handlePressMarker = async (event) => {
  // console.log('handlePressMarker', event);

  // if(selectedDefectInfo.value){
  //   selectedDefect.value = selectedDefectInfo.value
  // } else {
  const imageData = await loadInfoImageDefect(event.id)
  selectedDefect.value = {
    id: event.id,
    longitude: event.lnglat.lng,
    latitude: event.lnglat.lat,
    ...imageData
  }
  // }
  showModal()
}

const loadInfoImageDefect = async (id) => {
  if (!id) {
    return
  }
  const url = `http://luyisheng-api.xiyuefa.cn/luyisheng/doctorRoad/roadImage/queryDiseaseInfo?id=${id}`
  const res = await axios.get(url, {
    headers: {
      'Content-Type': 'application/json' // 设置请求头为 JSON 格式
    },
  });
  const data = res.data
  // console.log("result 123 ==>", data)
  if (!data || !data.success) {
    return
  }
  return data.result
}


const onPageChange = async (pagination) => {
  defectPages.current = pagination.current
  await loadListData()
}

const handleClickDefectRow = (event) => {
  console.log('handleClickDefectRow', event);
  selectedDefectInfo.value = event.extra
  mapView.value.moveToMarker(event.extra);
  // mapView.value.doubleClickAndMoveToMarker(event.extra);
}

const handleDoubleClickDefectRow = (event) => {
  // console.log('mapView.value ==>', mapView.value);
  // mapView.value.doubleClickAndMoveToMarker(event.extra);
}

// const formatDate = (dateString) => {
//   const date = new Date(dateString);
//   const year = date.getFullYear();
//   const month = String(date.getMonth() + 1).padStart(2, "0");
//   const day = String(date.getDate()).padStart(2, "0");
//   return `${year}-${month}-${day}`;
// }

// const parseCoordinates = (str) => {
//   //"靳桃线（靳店-南桃湾）1.MP4_36.4953642_110.979484_1114.715_847.jpg"
//   const regex = /_(\d+\.\d+)_(\d+\.\d+)_/;
//   const match = str.match(regex);
//   if (match) {
//     const lat = Number(match[1]);
//     const lng = Number(match[2]);
//     return [lng, lat];
//   } else {
//     return null;
//   }
// }

const loadTotalData = async () => {

  let url = `http://luyisheng-api.xiyuefa.cn/luyisheng/doctorRoad/roadImage/dataStatistics`;
  const res = await axios.get(url, {
    headers: {
      'Content-Type': 'application/json', // 设置请求头为 JSON 格式
    },
  });
  if (res.data && res.data.result) {
    totalInfo.value = {
      allStats: res.data.result.diseaseCount,
      allRoute: res.data.result.coveredRoadsCount
    }
  }


  const cacheKey = 'totalDataCache'
  const cacheData = localStorage.getItem(cacheKey)
  var totalJSONData;
  if (cacheData) {
    // 如果缓存存在，则从缓存中读取数据
    totalJSONData = JSON.parse(cacheData)
    // totalInfo.value = totalJSONData
  } else {
    // 如果缓存不存在，则从服务器获取数据   39005
    const response = await fetch("http://220.194.128.226:39005/statsDefects");

    totalJSONData = await response.json();
    console.log("totalJSONData = ", totalJSONData)
    // 将获取到的数据存储到缓存中，并设置过期时间为24小时
    localStorage.setItem(cacheKey, JSON.stringify(totalJSONData))
    localStorage.setItem(`${cacheKey}:expire`, (Date.now() + 24 * 60 * 60 * 1000).toString())
  }
  // totalInfo.value = totalJSONData

  let _categoryList = [];
  // console.log(`totalJSONData.event_type_stats=`, totalJSONData.event_type_stats);
  for (const eventType in totalJSONData.event_type_stats) {

    const count = totalJSONData.event_type_stats[eventType];
    // console.log(`${eventType}: ${count}`);
    // console.log(`${eventType}: ${count}`);
    _categoryList.push({
      value: count,
      name: eventType
    })
  }
  categoryList.value = _categoryList;



  // for (const eventType in totalJSONData.routeStats) {
  //   const count = totalJSONData.routeStats[eventType];
  //   // console.log(`${eventType}: ${count}`);
  //   // console.log(`${eventType}: ${count}`);
  //   if (!eventType) {
  //     continue;
  //   }
  //   _routeList.push({
  //     value: count,
  //     name: eventType
  //   })
  // }
  // routeList.value = _routeList;

}

const getSearchInfo = () => {
  const beginDate = selectedRange.value ? selectedRange.value[0].format('YYYY-MM-DD') : ''//
  const endDate = selectedRange.value ? selectedRange.value[1].format('YYYY-MM-DD') : ''//

  const params = {
    pageNo: defectPages.current,
    pageSize: defectPages.pageSize,
  };
  if (beginDate) {
    params['beginDate'] = beginDate
  }
  if (endDate) {
    params['endDate'] = endDate
  }
  if (cascaderValue.value && cascaderValue.value.length > 0) {
    params['provinces'] = cascaderValue.value.join(',')
  }
  if (taskValue.value && taskValue.value.length > 0) {
    params['taskId'] = taskValue.value[0]
  }
  if (roadValue.value && roadValue.value.length > 0) {
    params['roadId'] = roadValue.value[0]
  }
  if (defectTypeValue.value && defectTypeValue.value.length > 0) {
    params['defectTypeIdList;'] = defectTypeValue.value.join(',')
  }
  return params
}


const loadListData = async () => {
  //http://220.194.128.226:39005/infodc/defectGet?beginDate=2023-05-02&endDate=2023-05-03&pageNo=20&pageSize=30
  //"http://220.194.128.226:39005/infodc/defectGet?beginDate=2023-05-02&endDate=2023-05-03&pageNo=1&pageSize=300"
  // console.log('selectedRange = ', selectedRange.value)
  // const beginDate = selectedRange.value ? selectedRange.value[0].format('YYYY-MM-DD') : ''//
  // const endDate = selectedRange.value ? selectedRange.value[1].format('YYYY-MM-DD') : ''//


  // const params = {
  //   pageNo: defectPages.current,
  //   pageSize: defectPages.pageSize,
  // };
  // if (beginDate) {
  //   params['beginDate'] = beginDate
  // }
  // if (endDate) {
  //   params['endDate'] = endDate
  // }
  // if (cascaderValue.value.length > 0) {
  //   params['provinces'] = cascaderValue.value.join(',')
  // }
  // if (taskValue.value.length > 0) {
  //   params['taskId'] = taskValue.value[0]
  // }
  // if (roadValue.value.length > 0) {
  //   params['roadId'] = roadValue.value[0]
  // }
  // if (defectTypeValue.value.length > 0) {
  //   params['defectTypeIdList;'] = defectTypeValue.value
  // }
  isDefectInfoDataLoading.value = true
  // 39005
  // const url = `http://220.194.128.226:39003/infodc/search?${qs.stringify(params)}`;
  let url = `http://luyisheng-api.xiyuefa.cn/luyisheng/doctorRoad/roadImage/list?${qs.stringify(getSearchInfo())}`;
  const result = await axios.get(url, {
    headers: {
      'Content-Type': 'application/json', // 设置请求头为 JSON 格式
    },
  });
  // console.log('res 12 ==》 ', result)
  if (!result.data) {
    message.error('大屏数据加载失败')
    return
  }
  // const response = await fetch(url);
  // const defectsJSONData = await response.json();

  const defectsJSONData = result.data.result
  // console.log('defectsJSONData', defectsJSONData)
  // let data = [];
  // defectsJSONData.records.map((defect) => {
  //   // image.defects.map((defect) => {
  //   //   data.push([defect.defect_type, defect.route, formatDate(defect.snap_date), parseCoordinates(image.image_id)])
  //   // })
  //   data.push([defect.defect_type, defect.route, defect.snap_date, [defect.longitude, defect.latitude]])
  // })

  // defectList.value = data

  defectPages.current = defectsJSONData.current
  defectPages.total = defectsJSONData.total
  defectPages.pages = defectsJSONData.pages

  // console.log('defectList.value', defectInfoList.value)
  defectInfoList.value = defectsJSONData.records
  isDefectInfoDataLoading.value = false

}

watch(() => {
  return cascaderValue.value
}, (_newValue, _oldValue) => {

  loadTaskData(undefined)
})


const handleCascaderChange = (value, selectedOptions) => {
  cascaderValue.value = value
  loadTaskData(undefined)
}

const loadCascaderData = selectedOptions => {
  // console.log("selectedOptions ==>", selectedOptions)
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;
  // console.log("targetOption ==>", targetOption)
  if (!targetOption) {
    return
  }
  if (selectedOptions.length == 1) {
    loadCitysData(targetOption.id)
  }
  if (selectedOptions.length == 2) {
    loadAreasData([selectedOptions[0].id, selectedOptions[1].id])
  }
};

const loadPrivicesData = async () => {
  try {
    const url = `http://220.194.128.226:39003/load_provinces/`;
    const res = await axios.get(url, {
      headers: {
        'Content-Type': 'application/json' // 设置请求头为 JSON 格式
      },
    });
    const result = res.data
    if (!result || result.length == 0) {
      return
    }
    // console.log("pJSONData ==>", result)
    const list = []
    result.map(item => {
      list.push({
        ...item,
        isLeaf: false
      })
    })
    cascaderOptions.value = list
  } catch (error) {

  }
}

const loadCitysData = async (provinceId) => {
  if (!provinceId) {
    return
  }
  try {
    const url = `http://220.194.128.226:39003/load_cities?province_id=${provinceId}`;
    const res = await axios.get(url, {
      headers: {
        'Content-Type': 'application/json' // 设置请求头为 JSON 格式
      },
    });
    const result = res.data
    if (!result || result.length == 0) {
      return
    }
    const list = []
    result.map(item => {
      list.push({
        ...item,
        isLeaf: false,
        children: []
      })
    })
    cascaderOptions.value[cascaderOptions.value.findIndex(item => item.id == provinceId)]['children'] = list
    // console.log("cascaderOptions value ==>", cascaderOptions.value)

  } catch (error) {

  }
}

const loadAreasData = async (value) => {
  try {
    const url = `http://220.194.128.226:39001/load_areas?city_id=${value[1]}`;
    const res = await axios.get(url, {
      headers: {
        'Content-Type': 'application/json' // 设置请求头为 JSON 格式
      },
    });
    const result = res.data
    if (!result || result.length == 0) {
      return
    }
    const pIndex = cascaderOptions.value.findIndex(item => item.id == value[0])
    const cIndex = cascaderOptions.value[pIndex].children.findIndex(item => item.id == value[1])

    cascaderOptions.value[pIndex]['children'][cIndex]['children'] = result
    // console.log("aJSONData ==>", result)
  } catch (error) {

  }

}

const loadTaskData = async (taskName) => {
  try {

    const params = {}
    if (taskName) {
      params['name'] = taskName
    }
    if (cascaderValue.value && cascaderValue.value.length > 0) {
      params['province'] = cascaderValue.value.join(',')
    }

    let url = `http://luyisheng-api.xiyuefa.cn/luyisheng/doctorRoad/doctorserverInspectiontask/taskList?${qs.stringify(params)}`;
    const res = await axios.get(url, {
      headers: {
        'deviceId': 'XYF00001',
        'sign': 'A5CB7DF0E0B92BA1F34D3D77EBD6BDEC',
        'Content-Type': 'application/json' // 设置请求头为 JSON 格式
      },
    });
    const result = res.data

    if (!result.success || !result.result) {
      return
    }

    taskOptions.value = result.result.records || []

  } catch (error) {

  }
}

const loadRoalData = async (roadName) => {
  try {
    // 127.0.0.1:8080
    // const url = `http://luyisheng-api.xiyuefa.cn/luyisheng/doctorRoad/doctorserverRoadsegment/roadList`;
    const params = {}
    if (roadName) {
      params['name'] = roadName
    }
    if (taskValue.value.length > 0) {
      params['taskId'] = taskValue.value[0]
    }
    let url = `http://luyisheng-api.xiyuefa.cn/luyisheng/doctorRoad/doctorserverInspectiontask/recordList?${qs.stringify(params)}`;

    const res = await axios.get(url, {
      headers: {
        'deviceId': 'XYF00001',
        'sign': 'A5CB7DF0E0B92BA1F34D3D77EBD6BDEC',
        'Content-Type': 'application/json' // 设置请求头为 JSON 格式
      },
    });
    const result = res.data
    // console.log("result ==>", result)
    if (!result.success || !result.result) {
      return
    }
    roadOptions.value = result.result || []
  } catch (error) {

  }
}

const getLocalStorageDefectsalData = async () => {
  const createTime = localStorage.getItem('defectsallLnglatDataCreateDate')
  if (!createTime) {
    await loadDefectsallData()
    return
  }
  const isMoreThan3Days = isMoreThan3DaysFunction(createTime, Date.now() + 24 * 60 * 60)
  if (!isMoreThan3Days) {
    return
  }
  await loadDefectsallData()
}

const loadDefectsallData = async () => {
  // let url = `http://220.194.128.226:39003/defects_stat?zoom=${Math.round(zoom)}`;
  // if (center && center.length > 1) {
  //     url = `http://220.194.128.226:39003/defects_stat?zoom=${Math.round(zoom)}&longtitude=${center[0]}&latitude=${center[1]}`;
  // }
  // let url = 'http://220.194.128.226:39003/defectsall_get'
  let url = `http://luyisheng-api.xiyuefa.cn/luyisheng/doctorRoad/roadImage/queryAllLocations`;

  const res = await axios.get(url, {
    headers: {
      'deviceId': 'XYF00001',
      'sign': 'A5CB7DF0E0B92BA1F34D3D77EBD6BDEC',
      'Content-Type': 'application/json' // 设置请求头为 JSON 格式
    },
  });
  const result = res.data.result

  if (!result || result.length == 0) {
    return []
  }

  localStorage.removeItem('defectsallLnglatDataCreateDate')
  await removeData('defectsallLnglatDataInfo')
  // console.log("loadMapZoomData markers ==>", markers)
  // localStorage.setItem('defectsallLnglatDataInfo', JSON.stringify({ createTime: (Date.now() + 24 * 60 * 60).toString(), defectsallLnglatData: result.length > 60000 ? result.slice(0, 60000) : result }))

  localStorage.setItem('defectsallLnglatDataCreateDate', (Date.now() + 24 * 60 * 60).toString())
  const newData = { id: 'defectsallLnglatDataInfo', content: JSON.stringify(result) };
  await addData(newData);

  // mapView.value.setMarkersData(result)
  // let largeData = { id: 'defectsallLnglatDataInfo', data: new Array(5000).fill("data").join("") };
  // addData(largeData);

  // setLargeItem('defectsallLnglatDataInfo', result);
  // localStorage.setItem('defectsallLnglatDataInfo', JSON.stringify(result))
  // localStorage.setItem('defectsallLnglatCreateTime', JSON.stringify((Date.now() + 24 * 60 * 60)))

}


// methods
// todo 处理 loading 展示
const loadData = async () => {

  await getLocalStorageDefectsalData()
  await loadListData();

  await loadTotalData();
  loadPrivicesData()

  loadTaskData(undefined)
  loadRoalData(undefined)

  // setTimeout(() => {
  loading.value = false
  // }, 500)
}

// todo 处理时间监听
const handleTime = () => {
  timeInfo.setInterval = setInterval(() => {
    const date = new Date()
    timeInfo.dateDay = formatTime(date, 'HH: mm: ss')
    timeInfo.dateYear = formatTime(date, 'yyyy-MM-dd')
    timeInfo.dateWeek = WEEK[date.getDay()]
  }, 1000)
}

const handlePressSearch = async () => {
  // defectInfoList.value = []
  // isLoadingAgain.value = true
  loadListData();
  // isLoadingAgain.value = false
  lbmLeftBottomRef.value.setSearchInfo(getSearchInfo())
}

const handlePressClear = async () => {
  isLoadingAgain.value = true

  selectedRange.value = null
  defectPages.current = 1
  defectPages.total = 0
  defectPages.pages = 0
  cascaderValue.value = []
  taskValue.value = []
  roadValue.value = []
  taskName.value = null
  roadName.value = null


  await loadListData();
  isLoadingAgain.value = false
}


const drawerVisible = ref<boolean>(false);

const creatorModalVisible = ref<boolean>(false);

const afterDrawerVisibleChange = (bool: boolean) => {
  console.log('visible', bool);
};

const showDrawer = () => {
  drawerVisible.value = true;
};

const showCreator = () => {
  creatorModalVisible.value = true;
};


const handlePressAI = () => {
  showDrawer();
}
const handlePressCreator = () => {
  console.log('handlePressCreator')
  showCreator();
}

const handleCreatorOk = (e: MouseEvent) => {
  console.log(e);
  creatorModalVisible.value = false;
};

</script>

<style lang="scss" scoped>
@import '@/assets/scss/index.scss';


$term-box-height: 240px;
$term-box-width: 400px;

.right-top {
  padding: 16px;

  ::v-deep .ant-btn-primary {
    background-color: rgba(19, 115, 129, 0.3);
    border-color: #2869a3;
  }
}

.time-text {
  font-size: 28px;
  color: #ff4242;
}

.title-top {
  position: relative;

  .title-area {
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    top: 15px;
    left: 0;
    right: 0;
    z-index: 99;


  }
}

.centerRight2 {
  padding: 16px;
  padding-top: 20px;
  // height: $term-box-height;
  height: 100%;
  width: $term-box-width;
  border-radius: 5px;

  .theInput {
    background-color: rgba(7, 7, 7, 0.336);
    color: white;
    padding: 8px;
    // border: 1px solid white;

    border: 1px solid #2869a3;
    // width: 500px;
    // font-size: 18px;

    &:focus {
      border: 1px solid rgb(0, 204, 255);
      box-shadow: 0 0 8px rgb(0, 204, 255);
    }
  }

  .map-modes {
    // background-color: pink;

    ::v-deep .ant-radio-button-wrapper {
      background-color: #020B0D;
      color: #ffffff;
    }

    ::v-deep .ant-radio-button-wrapper-checked {
      background-color: #2869a3;
      color: #ffffff;
    }

  }

  .terms-row {
    margin-top: 10px;
  }

  .select-option {
    margin-top: 10px;
    width: 100%;

    .selectData {
      color: #ffffff;
      padding: 8px;
      border: 1px solid #2869a3;
      width: 100%;

      ::v-deep .ant-select-selector {
        color: #ffffff !important;
        background-color: rgba(7, 7, 7, 0.336) !important;
        border: none !important;
        padding: 0 !important;
      }

      ::v-deep .ant-select-clear {
        color: #ffffff !important;
        background: rgba(7, 7, 7, 0.336) !important;
      }

      ::v-deep .ant-select-selection-item {
        color: #ffffff !important;
        background: rgba(7, 7, 7, 0.336) !important;
      }
    }
  }

  .range-row {
    margin-top: 10px;

    .theDatePicker {
      background-color: rgba(7, 7, 7, 0.336);
      color: white;
      padding: 8px;
      border: 1px solid #2869a3;
      width: 100%;

      .ant-picker-input-active {
        color: #ffffff !important;
      }

      ::v-deep .ant-picker-clear {
        color: #ffffff !important;
        background: rgba(7, 7, 7, 0.336) !important;

      }

      ::v-deep .ant-picker-input {
        input {
          color: #ffffff !important;
        }
      }
    }
  }

  .cascader-row {
    margin-top: 10px;

    .theCascader {
      color: #ffffff;
      padding: 8px;
      border: 1px solid #2869a3;
      width: 100%;

      ::v-deep .ant-select-selector {
        color: #ffffff !important;
        background-color: rgba(7, 7, 7, 0.336) !important;
        border: none !important;
        padding: 0 !important;
      }

      ::v-deep .ant-select-clear {
        color: #ffffff !important;
        background: rgba(7, 7, 7, 0.336) !important;

      }
    }
  }

  .categories-row {
    margin-top: 10px;
    color: #ffffff;

    ::v-deep .ant-checkbox-wrapper {
      color: #ffffff;
    }
  }

  .button-row {
    margin-top: 10px;

    ::v-deep .ant-btn-primary {
      background-color: rgba(19, 115, 129, 0.3);
      border-color: #2869a3;
    }
  }


  .theSelect {
    background-color: rgb(66, 66, 66);
    color: white;
    padding: 2px 7px;
    outline: none;
  }
}

.loading-again {
  height: 100%;
  width: 100%;

  display: flex;
  align-items: center;
  justify-content: center;
}

.image-area {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  max-width: 100%;
  max-height: 100%;
}
</style>
